<template>
  <div class="statistics-container">
    <h2 class="page-title">统计分析</h2>
    
    <!-- 时间范围选择 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="统计周期">
          <el-select v-model="queryParams.period" placeholder="请选择统计周期" @change="handlePeriodChange">
            <el-option label="今日" value="today"></el-option>
            <el-option label="本周" value="week"></el-option>
            <el-option label="本月" value="month"></el-option>
            <el-option label="本季度" value="quarter"></el-option>
            <el-option label="本年" value="year"></el-option>
            <el-option label="自定义" value="custom"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="queryParams.period === 'custom'" label="自定义时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="fetchStatisticsData">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 统计概览 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="data-card">
          <div class="data-card-header">
            <i class="el-icon-s-order"></i>
            <span>订单总量</span>
          </div>
          <div class="data-card-content">
            <span class="data-value">{{ stats.orderCount }}</span>
            <div class="data-trend" :class="stats.orderCountTrend > 0 ? 'up' : 'down'">
              <i :class="stats.orderCountTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              <span>{{ Math.abs(stats.orderCountTrend) }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="data-card">
          <div class="data-card-header">
            <i class="el-icon-money"></i>
            <span>销售额</span>
          </div>
          <div class="data-card-content">
            <span class="data-value">¥{{ stats.salesAmount.toFixed(2) }}</span>
            <div class="data-trend" :class="stats.salesAmountTrend > 0 ? 'up' : 'down'">
              <i :class="stats.salesAmountTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              <span>{{ Math.abs(stats.salesAmountTrend) }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="data-card">
          <div class="data-card-header">
            <i class="el-icon-user"></i>
            <span>新增用户</span>
          </div>
          <div class="data-card-content">
            <span class="data-value">{{ stats.newUserCount }}</span>
            <div class="data-trend" :class="stats.newUserCountTrend > 0 ? 'up' : 'down'">
              <i :class="stats.newUserCountTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              <span>{{ Math.abs(stats.newUserCountTrend) }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="data-card">
          <div class="data-card-header">
            <i class="el-icon-house"></i>
            <span>新增商家</span>
          </div>
          <div class="data-card-content">
            <span class="data-value">{{ stats.newMerchantCount }}</span>
            <div class="data-trend" :class="stats.newMerchantCountTrend > 0 ? 'up' : 'down'">
              <i :class="stats.newMerchantCountTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              <span>{{ Math.abs(stats.newMerchantCountTrend) }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 订单统计图表 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>订单趋势</span>
          </div>
          <div class="chart-container" ref="orderTrendChart"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>销售额趋势</span>
          </div>
          <div class="chart-container" ref="salesTrendChart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 商家销售排行 -->
    <el-card class="ranking-card">
      <div slot="header">
        <span>商家销售排行</span>
      </div>
      <el-table :data="merchantRanking" stripe style="width: 100%">
        <el-table-column type="index" label="排名" width="80"></el-table-column>
        <el-table-column prop="merchantId" label="商家ID" width="100"></el-table-column>
        <el-table-column prop="merchantName" label="商家名称" width="200"></el-table-column>
        <el-table-column prop="orderCount" label="订单数量" width="120"></el-table-column>
        <el-table-column prop="salesAmount" label="销售额" width="150">
          <template slot-scope="scope">
            ¥{{ scope.row.salesAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="percentage" label="占比" width="120">
          <template slot-scope="scope">
            <el-progress :percentage="scope.row.percentage" :color="getColorByPercentage(scope.row.percentage)"></el-progress>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 热销商品排行 -->
    <el-card class="ranking-card">
      <div slot="header">
        <span>热销商品排行</span>
      </div>
      <el-table :data="foodRanking" stripe style="width: 100%">
        <el-table-column type="index" label="排名" width="80"></el-table-column>
        <el-table-column prop="foodId" label="商品ID" width="100"></el-table-column>
        <el-table-column prop="foodName" label="商品名称" width="200"></el-table-column>
        <el-table-column prop="merchantName" label="所属商家" width="200"></el-table-column>
        <el-table-column prop="salesCount" label="销售数量" width="120"></el-table-column>
        <el-table-column prop="salesAmount" label="销售额" width="150">
          <template slot-scope="scope">
            ¥{{ scope.row.salesAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="percentage" label="占比" width="120">
          <template slot-scope="scope">
            <el-progress :percentage="scope.row.percentage" :color="getColorByPercentage(scope.row.percentage)"></el-progress>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 订单状态分布 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>订单状态分布</span>
          </div>
          <div class="chart-container" ref="orderStatusChart"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>支付方式分布</span>
          </div>
          <div class="chart-container" ref="paymentMethodChart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 引入echarts
import * as echarts from 'echarts'
import axios from 'axios'

export default {
  name: 'Statistics',
  data() {
    return {
      // 查询参数
      queryParams: {
        period: 'week',
        startDate: '',
        endDate: ''
      },
      // 日期范围
      dateRange: [],
      // 统计数据
      stats: {
        orderCount: 0,
        orderCountTrend: 0,
        salesAmount: 0,
        salesAmountTrend: 0,
        newUserCount: 0,
        newUserCountTrend: 0,
        newMerchantCount: 0,
        newMerchantCountTrend: 0
      },
      // 商家销售排行
      merchantRanking: [],
      // 热销商品排行
      foodRanking: [],
      // 图表实例
      charts: {
        orderTrend: null,
        salesTrend: null,
        orderStatus: null,
        paymentMethod: null
      }
    }
  },
  created() {
    // 设置默认时间范围
    this.setDefaultDateRange()
  },
  mounted() {
    // 初始化图表
    this.$nextTick(() => {
      this.initCharts()
      this.fetchStatisticsData()
    })
    
    // 监听窗口大小变化，重绘图表
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('resize', this.resizeCharts)
    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
  },
  methods: {
    // 设置默认时间范围
    setDefaultDateRange() {
      const now = new Date()
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
      
      // 本周的开始（周一）
      const weekStart = new Date(today)
      const day = today.getDay() || 7
      weekStart.setDate(today.getDate() - day + 1)
      
      // 本周的结束（周日）
      const weekEnd = new Date(weekStart)
      weekEnd.setDate(weekStart.getDate() + 6)
      
      // 格式化日期
      this.queryParams.startDate = this.formatDate(weekStart)
      this.queryParams.endDate = this.formatDate(weekEnd)
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 处理周期变化
    handlePeriodChange(period) {
      if (period !== 'custom') {
        const now = new Date()
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
        let startDate, endDate
        
        switch (period) {
          case 'today':
            startDate = today
            endDate = today
            break
          case 'week':
            // 本周的开始（周一）
            startDate = new Date(today)
            const day = today.getDay() || 7
            startDate.setDate(today.getDate() - day + 1)
            // 本周的结束（周日）
            endDate = new Date(startDate)
            endDate.setDate(startDate.getDate() + 6)
            break
          case 'month':
            // 本月的开始
            startDate = new Date(today.getFullYear(), today.getMonth(), 1)
            // 本月的结束
            endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0)
            break
          case 'quarter':
            // 本季度的开始
            const quarter = Math.floor(today.getMonth() / 3)
            startDate = new Date(today.getFullYear(), quarter * 3, 1)
            // 本季度的结束
            endDate = new Date(today.getFullYear(), (quarter + 1) * 3, 0)
            break
          case 'year':
            // 本年的开始
            startDate = new Date(today.getFullYear(), 0, 1)
            // 本年的结束
            endDate = new Date(today.getFullYear(), 11, 31)
            break
        }
        
        // 更新查询参数
        this.queryParams.startDate = this.formatDate(startDate)
        this.queryParams.endDate = this.formatDate(endDate)
        
        // 更新日期范围
        this.dateRange = [this.queryParams.startDate, this.queryParams.endDate]
      }
    },
    
    // 处理日期范围变化
    handleDateRangeChange(val) {
      if (val) {
        this.queryParams.startDate = val[0]
        this.queryParams.endDate = val[1]
      } else {
        this.queryParams.startDate = ''
        this.queryParams.endDate = ''
      }
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams.period = 'week'
      this.setDefaultDateRange()
      this.dateRange = [this.queryParams.startDate, this.queryParams.endDate]
      this.fetchStatisticsData()
    },
    
    // 初始化图表
    initCharts() {
      this.charts.orderTrend = echarts.init(this.$refs.orderTrendChart)
      this.charts.salesTrend = echarts.init(this.$refs.salesTrendChart)
      this.charts.orderStatus = echarts.init(this.$refs.orderStatusChart)
      this.charts.paymentMethod = echarts.init(this.$refs.paymentMethodChart)
    },
    
    // 调整图表大小
    resizeCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize()
        }
      })
    },
    
    // 获取统计数据
    fetchStatisticsData() {
      // 获取基础统计数据
      this.fetchBasicStats()
      
      // 获取商家销售排行
      this.fetchMerchantRanking()
      
      // 获取热销商品排行
      this.fetchFoodRanking()
      
      // 获取图表数据
      this.fetchChartData()
    },
    
    // 获取基础统计数据
    fetchBasicStats() {
      // 根据API文档 9.2 获取统计数据
      axios.get('/api/statistics/summary', {
        params: {
          startDate: this.queryParams.startDate,
          endDate: this.queryParams.endDate
        }
      })
        .then(response => {
          if (response.data.code === 200) {
            const data = response.data.data
            this.stats = {
              orderCount: data.orderCount || 0,
              orderCountTrend: data.orderCountTrend || 0,
              salesAmount: data.salesAmount || 0,
              salesAmountTrend: data.salesAmountTrend || 0,
              newUserCount: data.newUserCount || 0,
              newUserCountTrend: data.newUserCountTrend || 0,
              newMerchantCount: data.newMerchantCount || 0,
              newMerchantCountTrend: data.newMerchantCountTrend || 0
            }
          } else {
            this.$message.error(response.data.message || '获取统计数据失败')
          }
        })
        .catch(error => {
          console.error('获取统计数据失败', error)
          this.$message.error('获取统计数据失败')
        })
    },
    
    // 获取商家销售排行
    fetchMerchantRanking() {
      // 根据API文档 9.3 获取商家销售排行
      axios.get('/api/statistics/merchant-ranking', {
        params: {
          startDate: this.queryParams.startDate,
          endDate: this.queryParams.endDate,
          limit: 10
        }
      })
        .then(response => {
          if (response.data.code === 200) {
            this.merchantRanking = response.data.data || []
          } else {
            this.$message.error(response.data.message || '获取商家销售排行失败')
          }
        })
        .catch(error => {
          console.error('获取商家销售排行失败', error)
          this.$message.error('获取商家销售排行失败')
        })
    },
    
    // 获取热销商品排行
    fetchFoodRanking() {
      // 根据API文档 9.4 获取热销商品排行
      axios.get('/api/statistics/food-ranking', {
        params: {
          startDate: this.queryParams.startDate,
          endDate: this.queryParams.endDate,
          limit: 10
        }
      })
        .then(response => {
          if (response.data.code === 200) {
            this.foodRanking = response.data.data || []
          } else {
            this.$message.error(response.data.message || '获取热销商品排行失败')
          }
        })
        .catch(error => {
          console.error('获取热销商品排行失败', error)
          this.$message.error('获取热销商品排行失败')
        })
    },
    
    // 获取图表数据
    fetchChartData() {
      // 根据API文档 9.5 获取订单趋势数据
      axios.get('/api/statistics/order-trend', {
        params: {
          startDate: this.queryParams.startDate,
          endDate: this.queryParams.endDate,
          period: this.queryParams.period
        }
      })
        .then(response => {
          if (response.data.code === 200) {
            const data = response.data.data || {}
            this.updateOrderTrendChart(data)
          } else {
            this.$message.error(response.data.message || '获取订单趋势数据失败')
          }
        })
        .catch(error => {
          console.error('获取订单趋势数据失败', error)
          this.$message.error('获取订单趋势数据失败')
        })
      
      // 根据API文档 9.6 获取销售额趋势数据
      axios.get('/api/statistics/sales-trend', {
        params: {
          startDate: this.queryParams.startDate,
          endDate: this.queryParams.endDate,
          period: this.queryParams.period
        }
      })
        .then(response => {
          if (response.data.code === 200) {
            const data = response.data.data || {}
            this.updateSalesTrendChart(data)
          } else {
            this.$message.error(response.data.message || '获取销售额趋势数据失败')
          }
        })
        .catch(error => {
          console.error('获取销售额趋势数据失败', error)
          this.$message.error('获取销售额趋势数据失败')
        })
      
      // 根据API文档 9.7 获取订单状态分布数据
      axios.get('/api/statistics/order-status', {
        params: {
          startDate: this.queryParams.startDate,
          endDate: this.queryParams.endDate
        }
      })
        .then(response => {
          if (response.data.code === 200) {
            const data = response.data.data || []
            this.updateOrderStatusChart(data)
          } else {
            this.$message.error(response.data.message || '获取订单状态分布数据失败')
          }
        })
        .catch(error => {
          console.error('获取订单状态分布数据失败', error)
          this.$message.error('获取订单状态分布数据失败')
        })
      
      // 根据API文档 9.8 获取支付方式分布数据
      axios.get('/api/statistics/payment-method', {
        params: {
          startDate: this.queryParams.startDate,
          endDate: this.queryParams.endDate
        }
      })
        .then(response => {
          if (response.data.code === 200) {
            const data = response.data.data || []
            this.updatePaymentMethodChart(data)
          } else {
            this.$message.error(response.data.message || '获取支付方式分布数据失败')
          }
        })
        .catch(error => {
          console.error('获取支付方式分布数据失败', error)
          this.$message.error('获取支付方式分布数据失败')
        })
    },
    
    // 更新订单趋势图表
    updateOrderTrendChart(data = {}) {
      const xAxisData = data.dates || []
      const seriesData = data.values || []
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xAxisData,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '订单数量',
            type: 'bar',
            barWidth: '60%',
            data: seriesData,
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      }
      
      this.charts.orderTrend.setOption(option)
    },
    
    // 更新销售额趋势图表
    updateSalesTrendChart(data = {}) {
      const xAxisData = data.dates || []
      const seriesData = data.values || []
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          },
          formatter: function(params) {
            return `${params[0].name}<br/>${params[0].seriesName}: ¥${params[0].value.toFixed(2)}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: xAxisData
          }
        ],
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              formatter: '¥{value}'
            }
          }
        ],
        series: [
          {
            name: '销售额',
            type: 'line',
            stack: '总量',
            areaStyle: {},
            emphasis: {
              focus: 'series'
            },
            data: seriesData,
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      }
      
      this.charts.salesTrend.setOption(option)
    },
    
    // 更新订单状态分布图表
    updateOrderStatusChart(data = []) {
      const statusMap = {
        1: { name: '待付款', color: '#E6A23C' },
        2: { name: '已付款', color: '#909399' },
        3: { name: '配送中', color: '#409EFF' },
        4: { name: '已完成', color: '#67C23A' },
        5: { name: '已取消', color: '#F56C6C' }
      }
      
      const chartData = data.map(item => ({
        value: item.count,
        name: statusMap[item.status]?.name || `状态${item.status}`,
        itemStyle: { color: statusMap[item.status]?.color }
      }))
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: chartData.map(item => item.name)
        },
        series: [
          {
            name: '订单状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: chartData
          }
        ]
      }
      
      this.charts.orderStatus.setOption(option)
    },
    
    // 更新支付方式分布图表
    updatePaymentMethodChart(data = []) {
      const methodMap = {
        1: { name: '微信支付', color: '#67C23A' },
        2: { name: '支付宝', color: '#409EFF' },
        3: { name: '校园卡', color: '#E6A23C' }
      }
      
      const chartData = data.map(item => ({
        value: item.count,
        name: methodMap[item.paymentMethod]?.name || `方式${item.paymentMethod}`,
        itemStyle: { color: methodMap[item.paymentMethod]?.color }
      }))
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: chartData.map(item => item.name)
        },
        series: [
          {
            name: '支付方式',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      
      this.charts.paymentMethod.setOption(option)
    },
    
    // 根据百分比获取颜色
    getColorByPercentage(percentage) {
      if (percentage >= 50) {
        return '#67C23A' // 绿色
      } else if (percentage >= 20) {
        return '#409EFF' // 蓝色
      } else {
        return '#E6A23C' // 黄色
      }
    }
  }
}
</script>

<style scoped>
.statistics-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.filter-card {
  margin-bottom: 20px;
}

.el-row {
  margin-bottom: 20px;
}

.data-card {
  height: 120px;
}

.data-card-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.data-card-header i {
  font-size: 20px;
  margin-right: 8px;
  color: #409EFF;
}

.data-card-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.data-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.data-trend {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.data-trend.up {
  color: #67C23A;
}

.data-trend.down {
  color: #F56C6C;
}

.data-trend i {
  margin-right: 4px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 400px;
}

.ranking-card {
  margin-bottom: 20px;
}
</style>